% Conditional on j and k, this code evaluates firm j's FOC w.r.t. p_jk2 
% at the candidate value x0, conditional on having a rate increase. 
function foc_out=foc_2nd(x0, cost2_1_jk, p_j1, claims_jk, s1_ind1_jj, ...
    resource_y2, B2_c, alpha, rho, crra, Delta_xi_jj, pr_y, U_lapse, cost_weight, use_cost_weight)
%% we're solving for p_jk2 (scalar) that satisfies the 2nd-period FOC
p_jk2 = x0; % scalar

%% predict lapse/stay probability conditional on p_jk2 & 2nd-period mkt share
% s_jk2: scalar
% stay_vec: N_y x 1
[s_jk2, stay_vec] = predict_s_jk2(p_jk2, s1_ind1_jj, Delta_xi_jj, U_lapse,...
    resource_y2, pr_y, B2_c, alpha, rho, crra);

%% deriv of s_jk2 w.r.t. p_jk2: see supply_estimation_lapse/D_s_price.m
c2 = resource_y2-p_jk2; % N_y x 1

D_v_p2 = -B2_c*alpha*D_u_c(c2, rho, crra); % N_y x 1

D_stay_p2 = D_v_p2.*stay_vec.*(1-stay_vec); % N_y x 1

deriv_sjk2_p2 = sum(s1_ind1_jj.*D_stay_p2.*pr_y); % scalar

N_y = length(pr_y);
claims_deriv_sjk2_p2 = sum(cost_weight.*repmat(claims_jk, N_y, 1).*s1_ind1_jj.*D_stay_p2.*pr_y); % scalar

%% FOC
if use_cost_weight==0
    foc_out = cost2_1_jk*(p_jk2 - p_j1) - s_jk2 - (p_jk2 - claims_jk)*deriv_sjk2_p2;
else
    foc_out = cost2_1_jk*(p_jk2 - p_j1) - s_jk2 - p_jk2*deriv_sjk2_p2 + claims_deriv_sjk2_p2;
end












